package com.ponhu.ea2.support.validation.validator;

import com.ponhu.ea2.support.exception.BusinessRuntimeException;
import com.ponhu.ea2.support.validation.annotions.ValidateExpression;
import lombok.extern.slf4j.Slf4j;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import static com.ponhu.ea2.enums.ResponseCodeEnum.PARAMETER_VALIDATE_EXCEPTION_800002;

/**
 * 表达式校验注解处理类
 * @author Wang
 * @date 2021/10/20 5:23 下午
 */
@Slf4j
public class ExpressionValidator implements ConstraintValidator<ValidateExpression, Object>  {

    private String expression;

    @Override
    public void initialize(ValidateExpression constraintAnnotation) {
        expression = constraintAnnotation.expression();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
        if(value == null){
            return false;
        }
        ExpressionParser parser = new SpelExpressionParser();
        Expression exp = parser.parseExpression(expression);
        try {
            boolean res = exp.getValue(value, Boolean.class);
            return res;
        } catch (EvaluationException e) {
            e.printStackTrace();
            throw new BusinessRuntimeException(PARAMETER_VALIDATE_EXCEPTION_800002.getCode(), e.getMessage());
        }
    }
}
